package com.aiti.lulian.controller;


import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.CardQuotationDto;
import com.aiti.lulian.entity.CardQuotation;
import com.aiti.lulian.entity.LuLianEnterpriseHistory;
import com.aiti.lulian.entity.LuLianEnterpriseUser;
import com.aiti.lulian.service.CardQuotationService;
import com.aiti.lulian.service.ILuLianEnterpriseUserService;
import com.aiti.lulian.service.ILulianEnterpriseHistoryService;
import com.aiti.lulian.vo.CardQuotationVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;


@RestController
@RequestMapping("/quotation")
@Api(tags = " quotation", description = "报价单管理")
public class CardQuotationController extends WebController {
    protected final Logger logger = LoggerFactory.getLogger(CardQuotationController.class);

    @Autowired
    private CardQuotationService cardQuotationService;

    @Autowired
    private ILuLianEnterpriseUserService enterpriseUserService;

    @Autowired
    private ILulianEnterpriseHistoryService enterpriseHistoryService;

    @ApiOperation(value = "报价单-分页")
    @GetMapping("findQuotationListPage")
    public Message findQuotationListPage(CardQuotationDto cardQuotationDto) {
        try {
            //检查当前是否为已登录状态
            String userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                System.out.println("------------------未登录------------------");
                return Fail("请先注册/登录！");
            }
            //检查是否为已认证企业的账号
            LambdaQueryWrapper<LuLianEnterpriseUser> enterpriseUserWrapper = new LambdaQueryWrapper<>();
            enterpriseUserWrapper.eq(LuLianEnterpriseUser::getUserId, userId);
            List<LuLianEnterpriseUser> enterpriseUserList = enterpriseUserService.list(enterpriseUserWrapper);
            List<String> enterpriseIds = enterpriseUserList.stream().map(LuLianEnterpriseUser::getEnterpriseId).collect(Collectors.toList());
            if (enterpriseIds == null || enterpriseIds.size() == 0) {
                enterpriseIds.add("0");
            }
            LambdaQueryWrapper<LuLianEnterpriseHistory> enterpriseHistoryWrapper = new LambdaQueryWrapper<>();
            enterpriseHistoryWrapper.in(LuLianEnterpriseHistory::getBaseId, enterpriseIds);
            int count = enterpriseHistoryService.count(enterpriseHistoryWrapper);
            if (count == 0) {
                return Fail("该账号未认证企业，请先进行企业认证！");
            } else if (count > 1) {
                return Fail("该账号关联了多个认证企业！");
            }else if (count == 1 && enterpriseUserList.size() > 1) {
                return Fail("该账号的企业关联记录存在多条！");
            }
            Integer pageSize = cardQuotationDto.getPageSize();
            Integer pageNum = cardQuotationDto.getPageNum();
            Page<CardQuotation> page = startPage(pageNum, pageSize);
            List<CardQuotationVo> list = cardQuotationService.findQuotationListPage(page, cardQuotationDto);
            return Success(getPageResult(list, pageNum, pageSize, (int) page.getTotal()));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Error(e.getMessage());
        }
    }


    @ApiOperation(value = "新增报价单")
    @PostMapping("add")
    public Message save(@RequestBody CardQuotationDto cardQuotationDto) {
        try {
            if (cardQuotationDto == null) {
                logger.error("新增异常：===》入参异常");
                return Message.fail("入参异常");
            }
            //检查当前是否为已登录状态
            String userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                System.out.println("------------------未登录------------------");
                return Fail("请先注册/登录！");
            }
            //检查是否为已认证企业的账号
            LambdaQueryWrapper<LuLianEnterpriseUser> enterpriseUserWrapper = new LambdaQueryWrapper<>();
            enterpriseUserWrapper.eq(LuLianEnterpriseUser::getUserId, userId);
            List<LuLianEnterpriseUser> enterpriseUserList = enterpriseUserService.list(enterpriseUserWrapper);
            List<String> enterpriseIds = enterpriseUserList.stream().map(LuLianEnterpriseUser::getEnterpriseId).collect(Collectors.toList());
            if (enterpriseIds == null || enterpriseIds.size() == 0) {
                enterpriseIds.add("0");
            }
            LambdaQueryWrapper<LuLianEnterpriseHistory> enterpriseHistoryWrapper = new LambdaQueryWrapper<>();
            enterpriseHistoryWrapper.in(LuLianEnterpriseHistory::getBaseId, enterpriseIds);
            int count = enterpriseHistoryService.count(enterpriseHistoryWrapper);
            if (count == 0) {
                return Fail("该账号未认证企业，请先进行企业认证！");
            } else if (count > 1) {
                return Fail("该账号关联了多个认证企业！");
            } else if (count == 1 && enterpriseUserList.size() > 1) {
                return Fail("该账号的企业关联记录存在多条！");
            }
            // 新增报价单信息
            int res = cardQuotationService.addQuotation(cardQuotationDto);
            if (res > 0) {
                return Message.success("新增成功");
            } else {
                return Message.fail("新增失败");
            }
        } catch (Exception e) {
            logger.error("新增异常：===》" + e);
            return Error(e.getMessage());
        }
    }

    /**
     * 报价单信息回显
     */
    @ApiOperation(value = "报价单信息回显")
    @GetMapping("getQuotationById")
    public Message getQuotationById(String baseId) {
        try {
            CardQuotationVo cardQuotationVo = cardQuotationService.getQuotationById(baseId);
            return Success(cardQuotationVo);
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Error(e.getMessage());
        }
    }



    @ApiOperation(value = "修改报价单")
    @PutMapping("update")
    public Message updateQuotation(@RequestBody CardQuotationDto cardQuotationDto) {
        try {
            if (cardQuotationDto == null) {
                logger.error("修改异常：===》入参异常");
                return Message.fail("入参异常");
            }
            // 修改报价单信息
            int res = cardQuotationService.updateQuotation(cardQuotationDto);
            if (res > 0) {
                return Message.success("修改成功");
            } else {
                return Message.fail("修改失败");
            }
        } catch (Exception e) {
            logger.error("修改异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }


    @ApiOperation(value = "报价单信息逻辑删除")
    @PostMapping("updateQuotationById")
    public Message updateQuotationById(String baseId) {
        try {
            // 修改报价单信息(隐藏报价单信息)
            int res = cardQuotationService.updateQuotationById(baseId);
            if (res > 0) {
                return Message.success();
            } else {
                return Message.fail();
            }
        } catch (Exception e) {
            logger.error("修改异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

}
